/**
Zeke Elder - zbe@andrew.cmu.edu
Amal Chemmany - achemman@andrew.cmu.edu
Nishant Kumar - nkumar1@andrew.cmu.edu
15-637
4/2/2012
 **/

package edu.cmu.fithub.actions;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import edu.cmu.fithub.controller.Action;
import edu.cmu.fithub.db.DBHelper;
import edu.cmu.fithub.db.bean.Friend;
import edu.cmu.fithub.db.bean.User;

public class AddFriendAction extends Action {

	public AddFriendAction() {
	}

	public String getName() {
		return "addFriend.do";
	}

	public String perform(HttpServletRequest request) {
		List<String> errors = new ArrayList<String>();
		request.setAttribute("errors", errors);
		try {
			Friend friend = new Friend();
			User user = (User) request.getSession().getAttribute("user");
			String friendId = request.getParameter("id");
			friend.setFriendId(Integer.parseInt(friendId));
			friend.setUserId(user.getUserId());

			Session dbSession = DBHelper.getSessionFactory().openSession();

			// check if friend already exists
			List<Friend> friend_list = dbSession
					.createCriteria(Friend.class)
					.add(Restrictions.eq("userId", user.getUserId()))
					.add(Restrictions.eq("friendId", Integer.parseInt(friendId)))
					.list();
			if (friend_list.size() != 0) {
				return "redirectToHome.jsp";
			}

			List<User> friendUser = dbSession.createCriteria(User.class)
					.add(Restrictions.eq("userId", friend.getFriendId()))
					.add(Restrictions.ne("userId", user.getUserId())).list();
			String friendName = friendUser.get(0).getFirstName();
			friend.setFriendName(friendName);
			dbSession.beginTransaction();
			dbSession.save(friend);
			dbSession.getTransaction().commit();
		} catch (NumberFormatException e) {
			errors.add(e.getMessage());
			return "error.jsp";
		}

		return "redirectToHome.jsp";
	}
}
